import sys
sys.path.append('.')
import os
import numpy as np

from util.PATH import PATH
from src.data_helper import DataHelper

class Model(object):
	'''
		分析真实修复者的分布情况
	'''
	def __init__(self, name, folder=None):
		print('start')
		self.name = name
		self.path = PATH(self.name)
		self.folder = folder
		data_helper = DataHelper(self.path)
		self.bug_msg_all, _ = data_helper.get_msg_all()
		self.time_windows = data_helper.split_dataset_by_eight_one_one(self.bug_msg_all)
		# self.time_windows = data_helper.read_dataset_by_category()
		self.developers = data_helper.create_developers_list()
	
	def count_distribution_in_train_and_rest(self,train_set, rest_set):
		train_dis = [0 for _ in range(len(self.developers))]	# 对应开发者的出现次数
		rest_dis = [0 for _ in range(len(self.developers))]
		for bugid in train_set:
			fixer = self.bug_msg_all[bugid][0]
			id_fixer = self.developers.index(fixer)
			train_dis[id_fixer] += 1
		for bugid in rest_set:
			fixer = self.bug_msg_all[bugid][0]
			id_fixer = self.developers.index(fixer)
			rest_dis[id_fixer] += 1
		
		with open(os.path.join(self.path.root, 'developer_dis.csv'), 'w') as writer:
			for i in range(len(self.developers)):
				writer.write('{},{},{}\n'.format(self.developers[i], str(train_dis[i]), str(rest_dis[i])))
	def split_dataset_by_same_category_eight_one_one(self,):
		'''
			按类别8：2划分，保证训练集训练过的修复者在测试集中都出现过，反之也一样
		'''
		bug_ids = sorted(self.bug_msg_all.keys())  # 升序排列
		ids_every_dever = [[] for _ in range(len(self.developers))]	# 统计每个修复者修复的所有bug的id
		for bugid in bug_ids:
			fixer = self.bug_msg_all[bugid][0]
			id_fixer = self.developers.index(fixer)
			ids_every_dever[id_fixer].append(bugid)
		train_set = []
		val_set = []
		test_set = []
		for info in ids_every_dever:
			delta = int(len(info)/10)		# len(info为)
			train_set += info[:int(delta*8)]
			val_set += info[int(delta*8) : delta*9]
			test_set += info[delta*9:]
		def save_set(datas, sign):
			with open(os.path.join(self.path.root, '{}.txt'.format(sign)), 'w') as writer:
				# [writer.write('{}\n'.format(str(datas[i]
				# )) for i in range(len(datas)))]
				for i in range(len(datas)):
					writer.write('{}\n'.format(datas[i]))

		save_set(train_set, 'train')
		save_set(val_set, 'val')
		save_set(test_set, 'test')


if __name__ == "__main__":
	model = Model('OpenOffice')
	model.split_dataset_by_same_category_eight_one_one()
	# print(model.bug_msg_all.keys())
	# model.count_distribution_in_train_and_rest(model.time_windows[0], model.time_windows[1] + model.time_windows[2])
